import json

# 定义商品目录
products = {
    "001": {"name": "苹果", "price": 10},
    "002": {"name": "樱桃", "price": 20},
    "003": {"name": "蓝莓", "price": 30},
}

# 定义用户信息文件路径
user_file = "users.json"

# 加载用户信息
def load_users():
    try:
        with open(user_file, "r") as f:
            users = json.load(f)
    except:
        users = {}
    return users

# 保存用户信息
def save_users(users):
    with open(user_file, "w") as f:
        json.dump(users, f)

# 注册新用户
def register():
    users = load_users()
    username = input("请输入用户名：")
    if username in users:
        print("该用户名已存在，请重新输入")
        return
    password = input("请设置密码：")
    budget = int(input("请输入预算金额："))
    rest_money = budget
    users[username] = {"password": password, "budget": budget, "rest_money":rest_money, "purchased": {}}
    save_users(users)
    print("注册成功！")

# 登录验证
def login():
    users = load_users()
    username = input("请输入用户名：")
    password = input("请输入密码：")
    if (username in users) & (users[username]["password"] == password) :
        print("验证成功！")
        return users[username]
    else:
        print("用户名或密码错误！请重新输入")
        return login()


# 查看商品目录
def view_products():
    print("商品编号\t商品名称\t商品价格")
    for id, product in products.items():
        print(f"{id}\t{product['name']}\t{product['price']}")

# 查看已购商品--购物车
def view_purchased():
    print("已购商品编号\t已购商品名称\t已购商品价格")
    for id, product in username["purchased"].items():
        print(f"{id}\t\t\t{product['name']}\t\t\t{product['price']}")
    print(f"当前余额为：{username['rest_money']}")

# 购买商品
def purchase():
    view_products()
    product_id = input("请输入要购买的商品编号：")
    if product_id not in products:
        print("商品编号不存在，请重新输入")
        return purchase()
    product = products[product_id]
    if product["price"] > username["rest_money"]:
        print("余额不足，请充值或退出购买")
        return
    username["rest_money"] -= product["price"]
    username["purchased"][product_id] = product
    save_users(users)
    print(f"购买成功！已购买商品：{product['name']}，花费：{product['price']}")

# 主函数

while True:
        print("欢迎来到三乐购物系统！")
        print("1. 注册账号")
        print("2. 登录账号")
        print("3. 退出系统(按q)")
        choice = input("请选择：")
        if choice == "1":
            register()
        elif choice =="2":
            users = load_users()
            username=login()
            while True:
                choice2 = input("请输入选择：\n1.购买\n2.查看购物车\n按q退出")
                if choice2 =="1":
                    purchase()
                elif choice2 =="2":
                    view_purchased()
                elif choice2 =="q":
                    break
        elif choice =="q":
            break
        else:
            print("输入不合法！")

